package cn.psh.user.service.impl;

import cn.psh.basic.constant.WxConstant;
import cn.psh.basic.dto.LoginDto;
import cn.psh.basic.jwt.JwtUtils;
import cn.psh.basic.jwt.LoginData;
import cn.psh.basic.jwt.RsaUtils;
import cn.psh.basic.util.AjaxResult;
import cn.psh.basic.util.HttpUtil;
import cn.psh.basic.util.MD5Utils;
import cn.psh.basic.util.StrUtils;
import cn.psh.basic.util.exception.BusinessException;
import cn.psh.org.mapper.EmployeeMapper;
import cn.psh.system.domain.Menu;
import cn.psh.system.mapper.MenuMapper;
import cn.psh.user.domain.Logininfo;
import cn.psh.user.domain.User;
import cn.psh.user.domain.Wxuser;
import cn.psh.user.mapper.LogininfoMapper;
import cn.psh.user.mapper.UserMapper;
import cn.psh.user.mapper.WxuserMapper;
import cn.psh.user.service.ILogininfoService;
import cn.psh.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pider
 * @since 2022-09-14
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private MenuMapper  menuMapper;


    @Override
    public Map<String, Object> account(LoginDto loginDto) {
//        空值校验
        final String account = loginDto.getAccount();
        final String password = loginDto.getPassword();
        final Integer type = loginDto.getType();
        if(StringUtils.isEmpty(account) || StringUtils.isEmpty(password) || StringUtils.isEmpty(type)){
            throw new BusinessException("数据不能为空！！");
        }
//        账号校验
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);//登录信息
        if(logininfo == null){
            throw new BusinessException("账号或密码不正确!");
        }
//        密码校验
        final String salt = logininfo.getSalt();
        final String md5 = MD5Utils.encrypByMd5(password + salt);
        if(!logininfo.getPassword().equals(md5)){
            throw new BusinessException("账号或者密码不正确");
        }
//        当前账号是否禁用
        if(logininfo.getDisable() == false){
            throw new BusinessException("该账号已被冻结，请联系管理员");
        }
//        生成token，并将登陆信息保存到redis，30分钟有效
//        final String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
//
////      返回token和logininfo对象
//        final HashMap<String, Object> map = new HashMap<>();
//        map.put("token", token);
////        敏感字段置空
//        logininfo.setSalt(null);
//        logininfo.setPassword(null);
//        map.put("logininfo", logininfo);
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        return map;
    }

    /**
     *
     * 微信扫码登陆
     * @param code
     * @return
     */
    @Override
    public AjaxResult wechatLogin(String code) {
        final String url = WxConstant.GET_ACK_URL.replace("APPID", WxConstant.APPID)
                .replace("SECRET", WxConstant.SECRET)
                .replace("CODE", code);
//        调用工具类发送请求，返回json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);
        JSONObject obj = JSONObject.parseObject(jsonStr);
        String access_token = obj.getString("access_token");
        String openid = obj.getString("openid");
//       根据openid查询wxuser表
        Wxuser wxuser = wxuserMapper.queryOpenid(openid);
        if(wxuser !=null){
//            oa9wA05-29HF36Mk5GGLK45nz1hQ
//            根据wxuser表里面的userid查询user对象，说明以前已经扫过直接免密登陆
            final User user = userMapper.queryById(wxuser.getUserId());
            if(user != null){
                final Logininfo logininfo = logininfoMapper.queryById(user.getLogininfoId());
//                final String token = UUID.randomUUID().toString();
//                redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
////      返回token和logininfo对象
//                final HashMap<String, Object> map = new HashMap<>();
//                map.put("token", token);
////        敏感字段置空
//                logininfo.setSalt(null);
//                logininfo.setPassword(null);
//                map.put("logininfo", logininfo);
                Map<String, Object> map = loginSuccessJwtHandler(logininfo);
                return AjaxResult.OJBK().setResultObj(map);
            }

        }
//        如果没有查到，就向前端响应token和openid并且前端跳转到绑定页面
        return AjaxResult.OJBK().setSuccess(false).setResultObj("?access_token="+access_token+"&openid="+openid);

    }

    /**
     * 微信绑定
     * @param map
     * @return
     */
    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
//        空值校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("数据不能为空");

        }
//        校验手机验证码
        final Object phonecode = redisTemplate.opsForValue().get("binder:" + phone);
        if(phonecode==null){
            throw new BusinessException("手机验证码过期，请重新获取！！");
        }
        if(!phonecode.toString().split(":")[0].equals(verifyCode)){
            throw new BusinessException("手机验证码错误，重新输入！！");
        }
//        组装第三个url
        String url = WxConstant.GET_USER_URL.replace("ACCESS_TOKEN", accessToken).
                replace("OPENID", openId);
//        发送http请求，并返回json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);

//        把json格式的字符串转换为json对象，并转换成一个wxuser
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);
        User user = userMapper.queryByPhone(phone);
        if(user == null){
//            创建user对象
            user= phone2User(phone);
//            创建logininfo对象
            Logininfo logininfo = user2Logininfo(user);
//           保存logininfo对象拿到自增id
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
//            再添加user对象
            userMapper.save(user);
        }
//        将user_id设置到wxuser里面，并保存wxuser
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        //八：免密登录
        Logininfo logininfoTemp = logininfoMapper.queryById(user.getLogininfoId());
//        String token = UUID.randomUUID().toString();//36位随机字符串
//        redisTemplate.opsForValue().set(token,logininfoTemp,30, TimeUnit.MINUTES);
//
//        //封住返回值：Map【token，logininfo】
//        Map<String, Object> mapTemp = new HashMap<>();
//        mapTemp.put("token",token);
//        logininfoTemp.setSalt(null);
//        logininfoTemp.setPassword(null);
//        mapTemp.put("logininfo",logininfoTemp);

        Map<String, Object> map1 = loginSuccessJwtHandler(logininfoTemp);
        //响应数据给前端
        return AjaxResult.OJBK().setResultObj(map1);
    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        try {
        HashMap<String, Object> map = new HashMap<>();
        LoginData loginData = new LoginData();
        map.put("logininfo",logininfo);
        loginData.setLogininfo(logininfo);
        if(logininfo.getType()==0){
//            获取当前登陆人的权限
            List<String> permission = employeeMapper.queryAllPermission(logininfo.getId());
            map.put("permission",permission);
//            设置permission
            loginData.setPermissions(permission);
//            查询当前登陆人的所有菜单
            List<Menu> menus = menuMapper.queryLoginAllMenu(logininfo.getId());
            map.put("menus",menus);
            loginData.setMenus(menus);
        }
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            final String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 3000000);
            map.put("token",jwtToken);

            return map;
        }catch (Exception e){
            e.printStackTrace();

        }
        return null;
    }



    private Logininfo user2Logininfo(User user) {
        final Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        final User user = new User();
        user.setUsername(phone);
        user.setPassword(phone);
        final String salt = StrUtils.getComplexRandomString(32);
        final String pwdTemp = StrUtils.getComplexRandomString(6);
        final String md5Pwd = MD5Utils.encrypByMd5(pwdTemp + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        final JSONObject obj = JSONObject.parseObject(jsonStr);
        final Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(obj.getString("openid"));
        wxuser.setNickname(obj.getString("nickname"));
        //现在微信已经将性别
        wxuser.setSex(Integer.parseInt(obj.getString("sex")));
        //地址：country + province + city
        wxuser.setHeadimgurl(obj.getString("headimgurl"));
        wxuser.setUnionid(obj.getString("unionid"));
        return wxuser;
    }
}
